package kayao.server;

import java.util.Vector;

import kayao.common.NetworkUtils;

public class GameManager {
	protected static float mFlagPositionX;
	protected static float mFlagPositionY;
	protected static float mFlagPositionZ;
	protected static int mCurrentMissionId;
	protected static float [][]mFlagPositions;
	protected static Vector<Vector<Collision>> mCollisions;
	
	private static int counter = 0;
	
	public static void initialize()
	{
		//mFlagPositions=new float[3][3];
		mFlagPositionX=0;
		mFlagPositionY=0;
		mFlagPositionZ=-10;
		mCurrentMissionId=0;
		mCollisions=new Vector<Vector<Collision>>();
		mCollisions.add(new Vector<Collision>());
	}
	
	private static float[]getCurrentPosition()
	{
		float []pos=new float[3];
		pos[0]=mFlagPositionX;
		pos[1]=mFlagPositionY;
		pos[2]=mFlagPositionZ;
		return pos;
	}
	public static byte[]getPositionBytes()
	{
		float []pos=getCurrentPosition();
		byte []bytes=new byte[12];
		int index=0;
		NetworkUtils.insertFloatToByteArray(bytes, index, pos[0]);
		index+=4;
		NetworkUtils.insertFloatToByteArray(bytes, index, pos[1]);
		index+=4;
		NetworkUtils.insertFloatToByteArray(bytes, index, pos[2]);
		index+=4;
		return bytes;
	}
	public static void createNewLocation()
	{
		// TODO Auto-generated method stub
		//Take random numbers to the position??
	}
	
	public static int getCurrentMissionId() 
	{
		return mCurrentMissionId;
	}

	public static void addCollision(int idApplicant, int missionId, int time) 
	{
		//Check if the guy already sent something
		for(int i=0;i<mCollisions.get(missionId).size();i++)
		{
			if(mCollisions.get(missionId).get(i).getId()==idApplicant)
			{
					if(mCollisions.get(missionId).get(i).getTime()<=time)
						return;
					else 
					{
						mCollisions.get(missionId).get(i).setTime(time);
						return;
					}
			}
		}
		//if it's his first message
		mCollisions.get(missionId).add(new Collision(idApplicant,time));
		//if it's the first in total
		if(isFirstCollision(missionId))
		{
			//create new mission
			createNewMission();			
			//tell everyone
			DesktopServer.sendNewMission();
		}
		
	}

	private static void createNewMission() 
	{
		if (counter == 0) {
			mFlagPositionX=0;
			mFlagPositionY=0;
			mFlagPositionZ=-20;
			counter++;
		} else if (counter == 1) {
			mFlagPositionX=-30;
			mFlagPositionY=0;
			mFlagPositionZ=0;
			counter++;
		} else if (counter == 2) {
			mFlagPositionX=30;
			mFlagPositionY=0;
			mFlagPositionZ=30;
			counter = 0;
		}
		createNewLocation();
		mCurrentMissionId++;
		mCollisions.add(new Vector<Collision>());
	}

	private static boolean isFirstCollision(int missionId) 
	{
		if(mCollisions.get(missionId).size()==1)
			return true;
		return false;
	}
}
